package jmu.cyxwcy.librarymanagement.controller;

import jakarta.validation.constraints.Pattern;
import jmu.cyxwcy.librarymanagement.pojo.*;
import jmu.cyxwcy.librarymanagement.service.IAdminService;
import jmu.cyxwcy.librarymanagement.service.UserService;
import jmu.cyxwcy.librarymanagement.utils.JwtUtil;
import jmu.cyxwcy.librarymanagement.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-06-24
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService iAdminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/add")
    public Result add(@RequestBody Admin admin){
        //查询用户
        Admin a = iAdminService.findByUserName(admin.getUsername());
        if(a==null){
            //添加
            String md5String = Md5Util.getMD5String(admin.getPassword());
            admin.setPassword(md5String);
            iAdminService.save(admin);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{1,16}$") String username, @Pattern(regexp = "^\\S{1,16}$") String password){
        //查询用户
        Admin admin = iAdminService.findByUserName(username);
        if(admin==null){
            return Result.error("账号错误");
        }
        if(Md5Util.getMD5String(password).equals(admin.getPassword())){
            //登录成功生成token
            Map<String,Object> claims=new HashMap<>();
            claims.put("username",admin.getUsername());
            //获得token令牌
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/findByUserName")
    public Result findByUserName(@RequestParam String username){
        Admin admin = iAdminService.findByUserName(username);
        return Result.success(admin);
    }

}
